package gui;

import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import client.CreditCard;
import client.LogIn;
import client.Main;
import client.MemberAccount;
import client.Subscribe;
import client.Delivery;
import gui.Cart_Gui;
import gui.SubscribeGUI;
import gui.CreditCard_GUI;


public class Payment_GUI extends JFrame implements ActionListener
{
	static int selection=-1;
	Double total=null;//for the subscribe after discount price
	public static Object[] rs=null;
	public String order_payment=null;
	public JButton Back=null;
	public JButton Back1=null;
	public JButton Subscriber=null;
	public JButton creditcard=null;
	public JButton cash=null;
	public JLabel title=null;
	public JLabel choosePayment=null;
	public JPanel panelMain=null;
	public JPanel panelCredit=null;
	public SubscribeGUI  sub=null;
	public CreditCard_GUI ccg=null;
	public CreditCard c=null;
	public Delivery x=null;
		
	public void hidePaymentScreen()
	{
		this.setEnabled(false);
		this.setVisible(false);
	}
	
	public void showPaymentScreen()
	{
		this.setEnabled(true);
		this.setVisible(true);
	}
	
	void init()
	{
		this.setSize(410,410);
		this.setTitle("Order Payment");
		this.setLocation((int)Main.dim.getWidth()/2 - (int)this.getPreferredSize().getWidth()/2,(int)Main.dim.getHeight()/4 - (int)this.getPreferredSize().getHeight()/4);
		this.add(getPanelMain());
		this.setResizable(false);	
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);	
		showPaymentScreen();
	}
	
	JPanel getPanelMain()
	{
		panelMain=new JPanel();
		panelMain.setLayout(null);
		panelMain.add(getButtonBack());
		panelMain.add(getLabelTitel("Checkout"));
		panelMain.add(getLabelChoosePayment());
		panelMain.add(getButtonCredit());
		panelMain.add(getButtonMember());
		panelMain.add(getButtonCash());
		panelMain.setVisible(true);
		panelMain.setEnabled(true);
		return panelMain;
	}
	
	
	
	JLabel getLabelTitel(String str)
	{
		title=new JLabel();
		title.setText(str);
		title.setBounds(130, 40, 300, 40);
		title.setFont(new Font(Font.SANS_SERIF ,Font.PLAIN,25));
		return title;
	}
	
	JLabel getLabelChoosePayment()
	{
		choosePayment=new JLabel();
		choosePayment.setText("Choose Way Of Payment:");
		choosePayment.setBounds(80, 105, 300, 40);
		choosePayment.setFont(new Font(Font.SANS_SERIF ,Font.PLAIN,18));
		return choosePayment;
	}
	JButton getButtonCredit()
	{
		if(creditcard==null)
		{
			creditcard=new JButton();
			creditcard.setText("Credit Card");
			creditcard.setBounds(80, 160, 220, 40);
			creditcard.addActionListener(this);
		}
		return creditcard;
	}
	JButton getButtonMember()
	{
		if(Subscriber==null)
		{
			Subscriber=new JButton();
			Subscriber.setText("Subscriber Card");
			Subscriber.setBounds(80,220,220,40);
			Subscriber.addActionListener(this);
		}
		return Subscriber;
	}
	
	JButton getButtonCash()
	{
		if(cash==null)
		{
			cash=new JButton();
			cash.setText("Cash");
			cash.setBounds(80,280,220,40);
			cash.addActionListener(this);
		}
		return cash;
	}
	
	JButton getButtonBack()//back of the main panel
	{
		if(Back==null)
		{
			Back=new JButton();
			Back.setText("Back");
			Back.setBounds(290,10,100,40);
			Back.addActionListener(this);
		}
		return Back;
	}	
	
	public void actionPerformed(ActionEvent e) 
	{
		if(e.getSource()== Back)//from main panel
		{
			int choice=-1;
			if(order_payment==null)
			{
				choice=JOptionPane.showConfirmDialog(null,"If you leave before paying your order will be canceled!\n Are u sure you want to leave?","Payment",JOptionPane.YES_NO_OPTION);
				if(choice==0)//0-yes 1-no
				{
					hidePaymentScreen();
					Main.main.showMainScreen();
				}
			}
			else 
			{
				JOptionPane.showMessageDialog(null,"Your order is saved","Payment",JOptionPane.INFORMATION_MESSAGE);
				hidePaymentScreen();
				Main.main.showMainScreen();
			}
		}

		if(e.getSource()== creditcard)
		{
			hidePaymentScreen();
			ccg=new CreditCard_GUI();
			ccg.Back.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					ccg.dispose();
					showPaymentScreen();
				}
			});
		}
		
		if(e.getSource()== Subscriber)
		{
			int uid=LogIn.usr.getID();
			Subscribe.checkSubscribe(uid);//checks if the user have a Subscriber card
			Long subscribeLong=(Long)rs[3];
			int subscribe=subscribeLong.intValue();
			
			if(subscribe>0)
			{
				int flag=checkIfDateExpiered(subscribe);
				if (flag==0)
				{
					int choice = JOptionPane.showConfirmDialog(null,"Your Subscriber card has expiers!\nDo you want to purches new one?","Subscriber",JOptionPane.YES_NO_OPTION);
					if(choice==0) 	getNewSubscribeCard();//0-yes 1-no
				}
				else
				{
					if(subscribe==1)//if has monthly card	
					{	
						total=(double) (Main.cart.total*0.9);
						JOptionPane.showMessageDialog(null,"Your monthly Subscriber card \nwill be charged with 10% discount:  \n"+total+" $ \n insead of: "+Main.cart.total+" $"," Cash Payment",JOptionPane.YES_NO_CANCEL_OPTION);
						order_payment="subscribe";
						approvePayment();
					}
					if(subscribe==2)//if has yearly card
					{
						total=(double) (Main.cart.total*0.8);
						JOptionPane.showMessageDialog(null,"Your yearly Subscriber card \nwill be charged with 20% discount:  \n"+total+" $ \n insead of: "+Main.cart.total+" $"," Cash Payment",JOptionPane.YES_NO_CANCEL_OPTION);
						order_payment="subscribe";
						approvePayment();
					}
				}
				System.out.println("subscribe: "+subscribe+"  order_payment:"+order_payment+" flag:"+flag);/**test print delete after**///
			}
			if(subscribe==0)
			{
				int choice=0;
				choice=JOptionPane.showConfirmDialog(null,"You don't have a current Subscriber  card!\nDo you want to purches???","Subscriber",JOptionPane.OK_CANCEL_OPTION);
				if (choice==0)
				{
					getNewSubscribeCard();
					
				}
			}
		}
		if(e.getSource()== cash)
		{
			int choice=0;
			if (selection==1)//if delivery
			{
				choice=JOptionPane.showConfirmDialog(null,"Sorry: cash payment is available only for pick-up\n do you want to change from delivery to pick-up? ","Cash Payment",JOptionPane.OK_CANCEL_OPTION);
				if (choice==0) //if OK: call pick_up_gui - CANCEL = 2 , OK = 0
				{
					selection = 2;//pickup
					System.out.println("Pick up in store");
					JOptionPane.showMessageDialog(null,"Your Delivery is canceled\n\nCash payment is approved\n Your total is: "+Main.cart.total+"\nYour order will wait for you at the nearest store");
					order_payment="cash";
					approvePayment();
				}	
			}
			else //if pickUp
				if(selection==2) 
					{
						JOptionPane.showMessageDialog(null,"Cash payment is approved\n Your total is: "+Main.cart.total," Cash Payment ",JOptionPane.DEFAULT_OPTION);
						order_payment="cash";
						approvePayment();
					}	
		}
	}
	
///Class methods////////////////////////////////////////////////////////////////////////////	
	void getNewSubscribeCard()
	{
		hidePaymentScreen();
		sub = new SubscribeGUI();
		sub.btnBack.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent e)
			{		
				showPaymentScreen();
				sub.dispose();
				Subscriber.doClick();
			}
		});
	}

	
	
	int checkIfDateExpiered(int type)
	{
		int flag=0;
		SimpleDateFormat d=new SimpleDateFormat("dd/MM/yy");
		Calendar c=Calendar.getInstance();	
		//if monthly
		if( type==1)	c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH)-30);	
		//if yearly
		else c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH)-365);
		
		String startdate=(String) rs[4];//subscribe card start date from DB
		String []splitStartDate=new String[3];
		splitStartDate=startdate.split("/");
		
		String today=d.format(c.getTime());//today date
		String []splitTodayDate=new String[3];
		splitTodayDate=today.split("/");
		
		int startDateInt[]=new int[3]; //change start date from string to int for comparing
		for(int i=0;i<3;i++)									
			startDateInt[i]=Integer.parseInt(splitStartDate[i]);						
		
		int todayDateInt[]=new int[3];//change today date from string to int for comparing
		for(int i=0;i<3;i++)									
			todayDateInt[i]=Integer.parseInt(splitTodayDate[i]);	
		
		//comparing:
		if(startDateInt[2]>todayDateInt[2])flag=1;//if later year OK
		else if(startDateInt[2]==todayDateInt[2])//if same year: check month:
				if(startDateInt[1]>todayDateInt[1])flag=1;//if month later month OK
				else if(startDateInt[1]==todayDateInt[1])//if same month: check day:
					if(startDateInt[0]>=todayDateInt[0])flag=1;//if later or same day OK

		return flag;
	}
	
	void approvePayment()
	{
		if(order_payment=="subscribe")
		{
			total=total*-1;
			Integer id=LogIn.usr.getID();
			String uid=id.toString();
			String money=total.toString();
			MemberAccount.SetBalance(uid,money,"-1");
		}
		hidePaymentScreen();
		String str=Main.cart.deliveryGreeting.delivryName;
		String str1=Main.cart.deliveryGreeting.deliveryAddress;
		String str2=Main.cart.deliveryGreeting.deliveryPhone;
		String str3=Main.cart.deliveryGreeting.deliveryOid;
	
		Main.main.orderCallFrom = "Payment_GUI";
		Main.main.Orders.doClick();
	}
	///// constructor////////////////////////////////////////////////////////////////////////////	
	public Payment_GUI(int s)//constructor 
	{		
		super();
		selection=s;
		init();	
	}
}
